package com.example.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.reggie.common.BaseContext;
import com.example.reggie.entity.*;
import com.example.reggie.mapper.OrderMapper;
import com.example.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     */
    @Transactional
    public boolean submit(Orders orders) {
        //获取用户id
        Long userId = BaseContext.getCurrentId();
        User user=userService.getById(userId);
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        //addressBook_id 增加order表的数据 回显order_id
        Long addressBookId = orders.getAddressBookId();
        log.info("order_id:{}",orders.getId());
        //获取本人user_id购物车的菜品和套餐 set总金额
        LambdaQueryWrapper<ShoppingCart>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        //该用户所有的购物车
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        //累加所有购物车的金额
        BigDecimal bigDecimal=new BigDecimal(0);

        orders.setPhone(user.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName());
        orders.setConsignee(user.getName());

        //随机生成订单id
        Long orderId = IdWorker.getId();
        log.info("订单id:{}",orderId);
        orders.setId(orderId);
        orders.setNumber(orderId.toString());
        //待插入的集合
        List<OrderDetail>orderDetailsList=new ArrayList<>();
        for (int i=0;i<list.size();i++){
            ShoppingCart item=list.get(i);

            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orderId);
            if (item.getDishId()!=null){
                orderDetail.setDishId(item.getDishId());
                orderDetail.setDishFlavor(item.getDishFlavor());
            }else {
                orderDetail.setSetmealId(item.getSetmealId());
            }
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            log.info("BigDecimal:{}",item.getAmount());
            bigDecimal=bigDecimal.add(item.getAmount());

            //加入到待插入order_detail表中的集合里
            orderDetailsList.add(orderDetail);
        }
        orders.setAmount(bigDecimal);
        log.info("要增加的order信息:{}",orders);

        //插入order表
        boolean orderSave = this.save(orders);
        //插入order_detail表
        boolean order_detailSave = orderDetailService.saveBatch(orderDetailsList);
        //清除本人购物车数据
        if (orderSave&&order_detailSave){
            LambdaQueryWrapper<ShoppingCart>queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(ShoppingCart::getUserId,userId);
            boolean remove = shoppingCartService.remove(queryWrapper1);
            if (remove){
            return true;
            }
        }
        return false;
    }

    /**
     * 用户下单
     * @param orderId
     */
    @Transactional
    public boolean buyAgain(Long orderId) {
        Orders orders=this.getById(orderId);
        //订单不存在
        if (null==orders){
            return false;
        }
        //用户id
        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<OrderDetail>queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,orderId);
        List<OrderDetail> orderDetailsList = orderDetailService.list(queryWrapper);
        List<ShoppingCart> shoppingCartList=new ArrayList<>();

        orderDetailsList.forEach((item)->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            shoppingCart.setUserId(userId);
            if (item.getDishId()!=null){
                shoppingCart.setDishId(item.getDishId());
                shoppingCart.setDishFlavor(item.getDishFlavor());
            }else {
                shoppingCart.setSetmealId(item.getSetmealId());
            }
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCartList.add(shoppingCart);
        });
        log.info("要加入购物车的集合:{}",shoppingCartList);
        boolean b = shoppingCartService.saveBatch(shoppingCartList);
        if (!b) {
            return false;
        }
        return true;
    }

}